package cn.hfatec.shms.web.members.ykBill.service;

import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.base.BaseDao;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.system.user.service.UserService;
import cn.hfatec.shms.web.members.cardType.dao.CardTypeDao;
import cn.hfatec.shms.web.members.cardType.model.CardType;
import cn.hfatec.shms.web.members.ykBill.dao.YkBillDao;
import cn.hfatec.shms.web.members.ykBill.model.YkBill;
import cn.hfatec.shms.web.members.ykBill.model.YkBillParams;
import cn.hfatec.shms.web.members.ykManage.model.YkManage;
import cn.hfatec.shms.web.members.ykManage.service.YkManageService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("YkBillService")
public class YkBillService {

    public static final String BEAN_ID = "YkBillService";

    //注入Dao层
    @Resource(name = "YkBillDao")
    private YkBillDao ykBillDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;
    //注入Dao层
    @Resource(name = "CardTypeDao")
    private CardTypeDao cardTypeDao;
    //服务层
    @Resource(name = "UserService")
    private UserService userService;
    //服务层
    @Resource(name = "YkManageService")
    private YkManageService ykManageService;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param ykBillParams
     * @param page
     */
    @Transactional
    public Table queryYkBillTable(YkBillParams ykBillParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", ykBillParams);
//        return baseDao.queryTableByPage("queryYkBill", params, page);
        return baseDao.queryTableByPage("queryOwnerCustomer", params, page);

    }

    /**
     * 插入数据
     *
     * @param ykManage
     */
    @Transactional
    public void saveYkBill(YkManage ykManage) {
        String cardId = ykManage.getCardId();
        Integer vipId = ykManage.getVipId();
        CardType cardType = cardTypeDao.getCardTypeById(vipId);
        Integer vipType = cardType.getVipType();
        YkBill ykBillR = ykBillDao.getYkBillByVipID(cardId, vipType);
        if (ykBillR != null) {
            YkBill ykBill = new YkBill();
            ykBill.setId(ykBillR.getId());
            ykBill.setUpManageId(ykBillR.getYkManageId());
            ykBill.setUpHealthCh(ykBillR.getHealthCh());
            ykBill.setUpHealthFg(ykBillR.getHealthFg());
            ykBill.setUpHealthYj(ykBillR.getHealthYj());
            ykBill.setUpVipFh(ykBillR.getVipFh());
            ykBill.setUpVipId(ykBillR.getVipId());
            ykBill.setYkManageId(ykManage.getBillId());
            ykBill.setVipId(ykManage.getVipId());
            ykBill.setEndDate(ykManage.getEndDate());
            ykBill.setHealthYj(ykManage.getHealthYj());
            ykBill.setHealthCh(ykManage.getHealthCh());
            ykBill.setHealthFg(ykManage.getHealthFg());
            ykBill.setVipFh(ykManage.getVipFh());
            ykBill.setCreateTime(ykManage.getCreateTime());
            ykBill.setCreateUser(ykManage.getCreateUser());
            ykBillDao.update(ykBill);
        } else {
            YkBill ykBill = new YkBill();
            ykBill.setYkManageId(ykManage.getBillId());
            ykBill.setVipId(vipId);
            ykBill.setCardId(cardId);
            ykBill.setStartDate(ykManage.getStartDate());
            ykBill.setEndDate(ykManage.getEndDate());
            ykBill.setHealthYj(ykManage.getHealthYj());
            ykBill.setHealthCh(ykManage.getHealthCh());
            ykBill.setHealthFg(ykManage.getHealthFg());
            ykBill.setVipFh(ykManage.getVipFh());
            ykBill.setCreateTime(ykManage.getCreateTime());
            ykBill.setCreateUser(ykManage.getCreateUser());
            ykBillDao.insert(ykBill);
        }
    }

    /**
     * 更新数据
     *
     * @param ykManage
     */
    @Transactional
    public void updateYkBill(YkManage ykManage) {
        String cardId = ykManage.getCardId();
        Integer vipId = ykManage.getVipId();
        CardType cardType = cardTypeDao.getCardTypeById(vipId);
        Integer vipType = cardType.getVipType();
        YkBill ykBill = ykBillDao.getYkBillByVipID(cardId, vipType);
        if (ykBill != null) {
            if (ykManage.getBillId().equals(ykBill.getYkManageId())) {
                ykBill.setVipId(ykManage.getVipId());
                ykBill.setCardId(ykManage.getCardId());
                ykBill.setStartDate(ykManage.getStartDate());
                ykBill.setEndDate(ykManage.getEndDate());
                ykBill.setHealthYj(ykManage.getHealthYj());
                ykBill.setHealthCh(ykManage.getHealthCh());
                ykBill.setHealthFg(ykManage.getHealthFg());
                ykBill.setVipFh(ykManage.getVipFh());
                ykBill.setCreateTime(ykManage.getCreateTime());
                ykBill.setCreateUser(ykManage.getCreateUser());
                ykBillDao.update(ykBill);
            } else if (ykManage.getBillId().equals(ykBill.getUpManageId())) {
                ykBill.setUpVipId(ykManage.getVipId());
                ykBill.setUpHealthYj(ykManage.getHealthYj());
                ykBill.setUpHealthCh(ykManage.getHealthCh());
                ykBill.setUpHealthFg(ykManage.getHealthFg());
                ykBill.setUpVipFh(ykManage.getVipFh());
                ykBillDao.update(ykBill);
            }
        }

    }

    /**
     * 更新分管人员
     *
     * @param ykManage
     */
    @Transactional
    public void updateFGYkBill(YkManage ykManage) {
        String cardId = ykManage.getCardId();
        Integer vipId = ykManage.getVipId();
        CardType cardType = cardTypeDao.getCardTypeById(vipId);
        Integer vipType = cardType.getVipType();
        YkBill ykBill = ykBillDao.getYkBillByVipID(cardId, vipType);
        if (ykBill != null) {
            ykBill.setHealthFg(ykManage.getHealthFg());
            ykBillDao.update(ykBill);
        }

    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    public void deleteYkBill(Integer id) {

        ykBillDao.delete(id);
    }

    /**
     * 删除更新数据
     *
     * @param ykManage
     */
    @Transactional
    public void deleteUpdateYkBill(YkManage ykManage) {
        String cardId = ykManage.getCardId();
        Integer vipId = ykManage.getVipId();
        CardType cardType = cardTypeDao.getCardTypeById(vipId);
        Integer vipType = cardType.getVipType();
        YkBill ykBill = ykBillDao.getYkBillByVipID(cardId, vipType);
        if (ykBill != null) {
            if (ykManage.getBillId().equals(ykBill.getYkManageId())) {
                if (ykBill.getUpManageId() != null) {
                    YkManage yM = ykManageService.getYkManageBillID(ykBill.getUpManageId());
                    if (yM != null) {
                        ykBill.setVipId(yM.getVipId());
                        ykBill.setCardId(yM.getCardId());
                        ykBill.setStartDate(yM.getStartDate());
                        ykBill.setEndDate(yM.getEndDate());
                        ykBill.setHealthYj(yM.getHealthYj());
                        ykBill.setHealthCh(yM.getHealthCh());
                        ykBill.setHealthFg(yM.getHealthFg());
                        ykBill.setVipFh(yM.getVipFh());
                        ykBill.setCreateTime(yM.getCreateTime());
                        ykBill.setCreateUser(yM.getCreateUser());
                        ykBill.setYkManageId(yM.getBillId());
                        ykBillDao.update(ykBill);
                    }
                } else {
                    deleteYkBill(ykBill.getId());
                }
            }
        }


    }

    /**
     * 删除数据
     *
     * @param ykBillList
     */
    @Transactional
    public void deleteYkBillBatch(List<String> ykBillList) {
        for (String id : ykBillList) {
            deleteYkBill(Integer.valueOf(id));
        }
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    public YkBill getYkBill(Integer id) {

        return ykBillDao.getYkBillById(id);
    }

    /**
     * 查询有效，一月内到期 ，二月内到期 ，三月内到期，过期客户数量
     */
    @Transactional
    public int queryOverdueCustomer(Integer overdueType) {
        YkBillParams ykBillParams = new YkBillParams();
        ykBillParams.setOverdueType(overdueType);//过期客户
        List list = ykBillDao.queryOwnerCustomer(ykBillParams);
        return list.size();
    }

    /**
     * 查询有效，一月内到期 ，二月内到期 ，三月内到期，过期客户数量
     */
    @Transactional
    public int overdueFgCustomer(String userName, Integer overdueType) {
        YkBillParams ykBillParams = new YkBillParams();
        ykBillParams.setUserLoginName(userName);
        ykBillParams.setOverdueType(overdueType);//过期客户
        List list = ykBillDao.queryOwnerCustomer(ykBillParams);
        return list.size();
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(YkBillParams ykBillParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = ykBillDao.queryOwnerCustomer(ykBillParams);
            List nameList = new ArrayList();
            nameList.add("卡号");
            nameList.add("客户姓名");
            nameList.add("种类");
            nameList.add("产品名称");
            nameList.add("开卡日期");
            nameList.add("到期日期");
            nameList.add("引荐人");
            nameList.add("促会人");
            nameList.add("分管人");
            nameList.add("副会");
            nameList.add("上次产品名称");
            nameList.add("上次分管人");
            nameList.add("到期类型");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> vipTypeList = CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE);
        List<CodeInfo> overdueTypeList = CodeInfoCache.getCodeInfo(CodeType.OVERDUE_TYPE);

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("会员信息表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        YkBill ykBill = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            ykBill = (YkBill) fieldData.get(i);
            // 第四步，创建单元格，并设置值
            row.createCell((short) 0).setCellValue(ykBill.getCardId());
            if (ykBill.getCustomerName() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(ykBill.getCustomerName());
            }
            if (ykBill.getVipType() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {

                for (CodeInfo c : vipTypeList) {//汉化性别信息
                    if (c.getValue().equals(ykBill.getVipType() + "")) {
                        row.createCell((short) 2).setCellValue(c.getContent());
                        break;
                    }
                }
            }
            if (ykBill.getProductName() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(ykBill.getProductName());
            }

            if (ykBill.getStartDate() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                String str = getDateTime(new String(String.valueOf(ykBill.getStartDate())));
                row.createCell((short) 4).setCellValue(str);
            }
            if (ykBill.getEndDate() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                String str = getDateTime(new String(String.valueOf(ykBill.getEndDate())));
                row.createCell((short) 5).setCellValue(str);
            }
            if (ykBill.getHealthYj() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {
                String username = getUserName(ykBill.getHealthYj());
                row.createCell((short) 6).setCellValue(username);
            }
            if (ykBill.getHealthCh() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                String username = getUserName(ykBill.getHealthCh());
                row.createCell((short) 7).setCellValue(username);
            }
            if (ykBill.getHealthCh() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {
                row.createCell((short) 8).setCellValue(ykBill.getUserLoginName());
            }

            if (ykBill.getVipFh() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {
                row.createCell((short) 9).setCellValue(ykBill.getVipFh());
            }
            if (ykBill.getUpProductName() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                row.createCell((short) 10).setCellValue(ykBill.getUpProductName());
            }

            if (ykBill.getUpHealthFg() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                row.createCell((short) 11).setCellValue(ykBill.getUpUserNameFg());
            }

            if (ykBill.getOverdueType() == null) {
                row.createCell((short) 12).setCellValue("");
            } else {
                for (CodeInfo c : overdueTypeList) {//汉化性别信息
                    if (c.getValue().equals(ykBill.getOverdueType() + "")) {
                        row.createCell((short) 12).setCellValue(c.getContent());
                        break;
                    }
                }

            }
        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }


        return wb;
    }


    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }

    public String getDateTime(String time) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String str = format.format(date);
        return str;
    }


    public String getUserName(String username) {
        if (StringUtils.isNotBlank(username)) {
            if (username.contains(",")) {
                String[] array = username.split(",");
                String userName = "";
                for (String str : array) {
                    User user = userService.getUserByLoginName(str);
                    userName += user.getUserName() + ",";
                }
                username = userName;
            }
        }
        return username;
    }


}